var express = require('express');
var doSql = require('./db2.js')
var router = express.Router()
var bodyParser = require('body-parser');
var md5 = require('md5-nodejs');
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// var fs = require('fs');
var multer = require('multer');


router.post('/', function (req, res) {
    res.send('user')
})
//忘记密码——》修改密码
router.post('/amendPassword', urlencodedParser, (req, res) => {
    let { id, pass } = req.body;
    // console.log(pass);
    let sql = `update users set loginKey='${pass}' where id=${id}`
    // console.log(sql);
    doSql.doSql(sql).then((data) => {
        res.send(doSql.hand(data))
    })
})
//忘记密码——》密保
router.get('/erpd', function (req, res) {
    let { name } = req.query
    // SELECT qa, u.id FROM encrypted AS m, users AS u WHERE u.loginName = 'zzzzz'
    // SELECT m.qa,u.id FROM encrypted AS m,users AS u WHERE u.loginName='zzzzz' AND u.id=m.uid 
    var sql = `SELECT qa, u.id FROM encrypted AS m, users AS u WHERE u.loginName = '${name}'`;
    doSql.doSql(sql).then(data => {
        res.send(doSql.heal(data[0]))
    })

})
//忘记密码——》用户名
router.get('/username', function (req, res) {
    let { form } = req.query
    var sql = `select loginName from users where loginName='${form}'`;
    doSql.doSql(sql).then((data) => {
        if (data[0]) {
            res.send(JSON.stringify(doSql.hand('用户名正确')))
        } else {
            res.send(JSON.stringify(doSql.hand('用户名错误')))
        }
    })

})
//密保设置
router.post('/encrypted', urlencodedParser, function (req, res) {
    let { jsarr, id,questionID } = req.body 
	var sql = `insert into mibao (question,uid) values ('${jsarr}','${id}')`;
	if(questionID){
	  sql = `update mibao set question = '${jsarr}' where uid = '${id}' `
	}
    doSql.doSql(sql).then(data => {
        res.send(doSql.hand(data[0]))
    })

})

router.post('/getMiBao', urlencodedParser, function (req, res) {
    let { id } = req.body
    var sql = `select * from mibao where uid=?`;
    doSql.doSql(sql,[id]).then(data => {
        res.send(doSql.hand(data))
    })
})

//图片上传
var objMulter = multer({ dest: 'upload/' }); //文件名
/*头像规则 */
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'upload/')
    },
    // 保存文件名
    filename: function (req, file, cb) {
        let extName = file.originalname.slice(file.originalname.lastIndexOf('.'))
        cb(null, file.fieldname + '-' + Date.now() + extName)   /* 文件配置 */
    }
})

var objMulter = multer({ storage })
// 头像上传请求
router.post('/uploadIcon', objMulter.single('avatar'), (req, res, next) => {
    var file = req.file;
    // console.log(file);
    res.send(JSON.stringify(doSql.hand({ avatar: file.filename })))
})

//注册
router.post('/register', urlencodedParser, function (req, res) {
    let { name, age, gender, edu, loginName, loginKey, avatar, roles, introduction, email } = req.body
    var sql = `insert into users (name,age,gender,edu,loginName,loginKey,roles,avatar,introduction,email) values ('${name}','${age}','${gender}','${edu}','${loginName}','${loginKey}','${avatar}','${roles}','${introduction}','${email}')`;
    doSql.doSql(sql).then(data => {
        // console.log(data);
        // res.header("Access-Control-Allow-Origin", "*");
        // res.header("Content-Type", "text/html; charset=utf-8")
        res.send(doSql.hand(data[0]))
    })
})

// 验证用户名
router.get('/loginName', async function (req, res) {
    // SELECT * FROM `users` WHERE loginName like 'admin'
    let { loginName } = req.query;

    var sql = await doSql.doSql(`SELECT * FROM users WHERE loginName like '${loginName}'`);
    console.log(sql.resultes.length)
    res.send(doSql.hand(sql.resultes.length))
})

router.get('/findPass', async function (req, res) {
    let { loginName } = req.query;
    console.log(loginName)
    var sql = await doSql.doSql(`select count(*) as num ,u.id ,m.question from users u , mibao m where loginName = '${loginName}' and  u.id=m.uid`);
    res.send(doSql.hand(sql))
})

//登录接口
router.post('/login', urlencodedParser, function (req, res) {

    var username = req.body.username
    var password = req.body.password
    var sql = `select id,name,status,roles,avatar,introduction from users where loginName='${username}' and loginKey='${password}'`;

    doSql.doSql(sql).then(data => {
        if (data.code === 10000) {
            setTimeout(() => {
                res.send(data);
                return
            }, 3000);
        }
        if (data.resultes[0]) {
            console.log(data.resultes[0].id)
            getToken(data.resultes[0].id).then(tokens => {
                data.resultes[0].token = tokens
                res.send(doSql.hand(data.resultes[0]))
            })
        } else {
            res.send(doSql.fool())
        }
    })

})

//角色权限
router.get('/rolesMenus', function (req, res) {
    let { role } = req.query
    let sql = `select * from roles where role = '${role}'`
    doSql.doSql(sql).then(data => {
        console.log(data);
        res.send(doSql.hand(data.resultes[0]))
    })
})
// 角色列表
router.get('/roles', function (req, res) {
    getroles(req, res)
})
async function getroles(req, res) {
    var sql = await doSql.doSql(`select * from roles`);

    res.send(doSql.hand(sql.resultes))
}
// 修改用户角色
router.post('/userRoles', urlencodedParser, async function (req, res) {
    let { id, roles } = req.body;
    console.log(id, roles)
    var sql = await doSql.doSql(`update users set roles='${roles}'where id='${id}'`);

    res.send()
})

router.get('/info', function (req, res) {
    let { token } = req.query
    var sql = 'select u.id,name,roles,avatar,introduction from tokens as t,users as u where t.uid=u.id and t.token=?';
    doSql.doSql(sql, [token]).then(data => {
        data.resultes[0].roles = data.resultes[0].roles.split(',')
        res.send(doSql.hand(data.resultes[0]))
    })
})

router.get('/getroles', function (req, res) {
    let { roles } = req.query
    var sql = `select * from roles where role='${roles}'`;
    
    doSql.doSql(sql).then(data => {
        console.log(data.resultes[0])
        res.send(doSql.hand(data.resultes[0]))
    })
})
//删除
router.get('/delete', function (req, res) {
    // console.log(req.query);
    let id = req.query.id
    // console.log(id);
    // console.log(id);
    sql = `delete from users where id in(${id})`;
    doSql.doSql(sql).then(data => {
        // res.header("Access-Control-Allow-Origin", "*");
        // console.log(data);
        res.send(doSql.heal(data))
    })
    // res.header("Content-Type", "text/html; charset=utf-8")

})
//个人中心修改
router.post('/updates', urlencodedParser, function (req, res) {
    let { id, name, avatar, introduction } = req.body
    var sql = `update users set name='${name}',avatar='${avatar}',introduction='${introduction}' where id=${id}`
    doSql.doSql(sql).then(data => {
        res.send(doSql.hand(data[0]))
    })

})
//修改密码
router.post('/password', urlencodedParser, (req, res) => {
    let { id, oldpass, pass } = req.body;
    let sql = `update users set loginKey='${pass}' where id=${id}`
    if (oldpass) {
        sql = `update users set loginKey='${pass}' where id=${id} and loginKey='${oldpass}'`
    }
    doSql.doSql(sql).then((data) => {
		res.send(doSql.hand(data))
        console.log(data)
        res.send(doSql.hand(data))
        // res.send(doSql.hand(data[0]))
        // if (data.resultes.affectedRows) {
        // res.send(JSON.stringify(doSql.hand('密码修改成功')))
        // } else {
        // res.send(JSON.stringify(doSql.hand('原密码错误')))
        // }
    })
})

//修改状态
router.get('/update', urlencodedParser, function (req, res) {
    let { id, status } = req.query
    // console.log(id);
    // console.log(status);
    var sql = `update users set status='${status}' where id in (${id})`
    doSql.doSql(sql).then(data => {
        res.send(doSql.hand(data))
        // if (data.affectedRows == 1) {
        // } else {
        //     res.send(doSql.hand(data))
        // }
        // res.header("Access-Control-Allow-Origin", "*");
        // res.header("Content-Type", "text/html; charset=utf-8")

    })

})
//用户管理接口
router.get('/user', function (req, res) {
    getusers(req, res)
})
async function getusers(req, res) {
    var sqls = 'select id,name,age,loginName,gender,roles,status from users ';
    var { status, page, pageSize, keyword, order, prop } = req.query;
    if (!page) {
        page = 0
    }
    if (!pageSize) {
        pageSize = 20
    }
    var start = page * pageSize;
    if (status === "0") {
        sqls += `where status like 0`
        var sql = `select count(status=0) as total from users where status like 0`
        if (keyword) {
            sqls += ` and name like '%${keyword}%'`;
            sql += ` and name like '%${keyword}%'`
        }
        if (order) {
            sqls += ` order by ${order} ${prop}`
        }
        sqls += ` limit ${start},${pageSize} `

        var sql = await doSql.doSql(sql)
    } else {
        sqls += `where status like 1`;
        var sql = `select count(status=0) as total from users where status like 1`
        if (keyword) {
            sqls += ` and name like '%${keyword}%'`;
            sql += ` and name like '%${keyword}%'`
        }
        if (order) {
            sqls += ` order by ${order} ${prop}`
        }
        sqls += ` limit ${start},${pageSize}`;
        console.log(sqls)
        var sql = await doSql.doSql(sql)
    }
    const Sql = await doSql.doSql(sqls)
    console.log(sql)


    res.send(JSON.stringify(doSql.heal(Sql.resultes, sql.resultes[0].total)))
}
// router.get('/oficl', function (req, res) {
//     // let { orderby = 'id', sort = 'desc', keyword } = req.query
//     let { pages, pagesize, orderby = 'id', sort = 'desc', keyword } = req.query
//     if (!pages) {
//         pages = 0
//     }
//     if (!pagesize) {
//         pagesize = 20
//     }

//     let sum = pages * pagesize
//     var sql = `select * from users`;
//     var sqla = `select count(*) as total from users`;

//     if (keyword) {
//         sql += ` where name like '${keyword}%'`
//         sqla += ` where name like '${keyword}%'`
//     }

//     if (orderby) {
//         sql += ` order by ${orderby} ${sort}`
//     }

//     sql += ` limit ${sum},${pagesize}`

//     // console.log(sql);
//     // console.log(sqla);

//     var p1 = doSql.doSql(sql)
//     var p2 = doSql.doSql(sqla)
//     Promise.all([p1, p2]).then(data => {
//         // console.log(res);
//         res.send(JSON.stringify(doSql.heal(data[0], data[1][0].total)))
//     })

//     // doSql.doSql(sql).then(data => {
//     //     // res.send(doSql.heal(data, data[1][0].total))
//     //     res.send(doSql.hand(data))
//     // })
// })
//退出接口
router.post('/logout', urlencodedParser, function (req, res) {
    let { id } = req.body
    var sql = 'delete from tokens where uid=?'
    doSql.doSql(sql, [id]).then(data => {
        res.send(doSql.hand())
    })
})

function getToken(uid) {
    return new Promise((resolve, reject) => {
        var token;
        var sql = 'select token from tokens where uid=?'
        doSql.doSql(sql, [uid]).then(data => {

            if (data.length > 0 && data[0].token) {
                token = data.resultes[0].token
            } else {
                token = md5('zxwx' + uid + Date.now());
                saveToken(token, uid)
            }
            resolve(token)
        })
    })
}

function saveToken(token, uid) {
    var sql = 'insert into tokens (token,uid) values (?,?)'
    doSql.doSql(sql, [token, uid])
}


module.exports = router